package com.example.myproject.jackson;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.databind.DeserializationContext;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * Created by xi on 2018/9/23.
 */
public class JacksonBigDeceimalDeSerializer  extends NewPrimitiveOrWrapperDeserializer<BigDecimal>{
    private static final long serialVersionUID = 1L;
    public final static JacksonBigDeceimalDeSerializer instance = new JacksonBigDeceimalDeSerializer();

    public JacksonBigDeceimalDeSerializer() { super(BigDecimal.class,null,null); }

    @Override
    public Object getEmptyValue(DeserializationContext ctxt) {
        return BigDecimal.ZERO;
    }

    @Override
    public BigDecimal deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException
    {
        switch (p.getCurrentTokenId()) {
            case JsonTokenId.ID_NUMBER_INT:
            case JsonTokenId.ID_NUMBER_FLOAT:
                return p.getDecimalValue();
            case JsonTokenId.ID_STRING:
                String text = p.getText().trim();
                // note: no need to call `coerce` as this is never primitive

                if (text.length() == 0) {
                    return  UpdateSpecialConstant.SPECIAL_BIGDECIMAL_VALUE;
                    // return (Date) getEmptyValue(ctxt);
                }
                if (_isEmptyOrTextualNull(text)) {
                    _verifyNullForScalarCoercion(ctxt, text);
                    return getNullValue(ctxt);
                }
                _verifyStringForScalarCoercion(ctxt, text);
                try {
                    return new BigDecimal(text);
                } catch (IllegalArgumentException iae) { }
                return (BigDecimal) ctxt.handleWeirdStringValue(_valueClass, text,
                        "not a valid representation");
            case JsonTokenId.ID_START_ARRAY:
                return _deserializeFromArray(p, ctxt);
        }
        // Otherwise, no can do:
        return (BigDecimal) ctxt.handleUnexpectedToken(_valueClass, p);
    }
}
